package com.sv.utils.ibatis;

import org.apache.commons.lang.StringUtils;

public class MysqlDialect implements Dialect {

    private static String SQL_END_DELIMITER = ";";

    public boolean supportLimit() {
        return true;
    }

    public String getLimitSql(String sql, boolean hasofferset) {
        sql = trimSqlEndDelimiter(sql);

        StringBuffer limitSql = new StringBuffer(sql);

        limitSql.append(supportLimit() ? " limit ?,?" : "");

        return limitSql.toString();
    }

    public String getLimitSql(String sql, int offset, int limit) {
        sql = trimSqlEndDelimiter(sql);

        StringBuffer limitSql = new StringBuffer(sql);

        if (offset > 0) {
            limitSql.append(" limit ").append(String.valueOf(offset))
                    .append(",").append(String.valueOf(limit))
                    .append(SQL_END_DELIMITER);
        }
        else {
            limitSql.append(" limit ").append(String.valueOf(limit))
                    .append(SQL_END_DELIMITER);
        }

        return limitSql.toString();
    }

    public String trimSqlEndDelimiter(String sql) {
        if (sql.lastIndexOf(SQL_END_DELIMITER) > 0) {
            return StringUtils.trim(sql.substring(0, sql.length() - 1));
        }
        return StringUtils.trim(sql);
    }
}
